import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/unallocated_department_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/unallocated_department_view_model.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/bean/company_detail_by_type_list_response_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/personal_details_information_widget/personal_class_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/personal_details_information_widget/personal_department_widget.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/update_task_view_model.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../../../app_main.dart';

/// 未分配部门 //--UnallocatedDepartmentStaffWidget
///

class UnallocatedDepartmentStaffWidget extends StatefulWidget {
  final int classOrDepartmentType;
  ///路由名称
  static const String ROUTER = "UnallocatedDepartmentStaffWidget";
  UnallocatedDepartmentStaffWidget({Key key, this.classOrDepartmentType})
      : super(key: key);

  @override
  _UnallocatedDepartmentStaffWidgetState createState() =>
      _UnallocatedDepartmentStaffWidgetState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context,int classOrDepartmentName) {
    return RouterUtils.routeForFutureResult(
      context,
      UnallocatedDepartmentStaffWidget(
          classOrDepartmentType:classOrDepartmentName
      ),
      routeName: UnallocatedDepartmentStaffWidget.ROUTER,
    );
  }
}

class _UnallocatedDepartmentStaffWidgetState extends BaseState<UnallocatedDepartmentStaffWidget>{
  bool selectAll = false; //是否全部选中
  UnallocatedDepartmentStaffViewModel viewModel;
  UnallocatedDepartmentBean unallocatedDepartmentBean;
  List<RecordsBean> recordsBeanList;
  String classOrDepartmentName = "";
  List<RecordsBean> selectRecordsBeanList;
  FaceUserInfoBean faceUserInfoBean;
  List<String> fuid;
  StreamSubscription updateunallocatedSubscription;
  @override
  void initState() {
    super.initState();
    selectRecordsBeanList = new List<RecordsBean>();
    unallocatedDepartmentBean = UnallocatedDepartmentBean();
    faceUserInfoBean = FaceUserInfoBean();
    recordsBeanList = List<RecordsBean>();
    viewModel = UnallocatedDepartmentStaffViewModel(this);
    viewModel.departmentValueStream.listen((value) {
      unallocatedDepartmentBean = value;
      recordsBeanList = unallocatedDepartmentBean?.data?.page?.records;
      selectAll =false;
      setState(() { });
    });
    _viewInit();
    updateunallocatedSubscription =
        VgEventBus.global.on<UpdateUnallocatedInfoRefreshEvent>().listen((event) {
          _viewInit();
        });
    widget?.classOrDepartmentType==0 ? classOrDepartmentName = "部门": classOrDepartmentName = "班级";
  }

  void _viewInit(){
    fuid = new List();
    viewModel?.unallocatedUser(context,(widget?.classOrDepartmentType??0).toString());
  }

  @override
  void dispose() {
    updateunallocatedSubscription.cancel();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
       Scaffold(
        resizeToAvoidBottomPadding: true,
        resizeToAvoidBottomInset: true,
        backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(
          children: <Widget>[
            _toTopBarWidget(),
            _toFunctionBar(),
            Expanded(child: _toListBean()),
            _button()
          ],
        ),
        // _toFunctionBar(),
      ),
      navigationBarColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  ///TopBar
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      title: "未分配${classOrDepartmentName??""}·${recordsBeanList?.length??0}人",
    );
  }

  Widget _button(){
    bool selectLength = (selectRecordsBeanList?.length??0) != 0;
    return Container(
      height: 40,
      width: 360,
      margin: const EdgeInsets.symmetric(vertical: 10),
      child: RaisedButton(
        onPressed: () {
          if(!AppOverallDistinguish.comefromAiOrWeStudy() && classOrDepartmentName != "部门"){
            VgToastUtils.toast(context, "请至蔚来一起学设置");
            return;}
          if(classOrDepartmentName!="" && selectLength){
            // selectRecordsBeanList?.forEach((element) {
            //   fuid?.add(element?.fuid);
            // });
            //如果是全部选中，那么则返回到部门界面
            if(fuid?.length == recordsBeanList?.length){
              faceUserInfoBean?.isSelectAll = true;
            }else faceUserInfoBean?.isSelectAll = false;
            faceUserInfoBean?.fuid = VgStringUtils?.getSplitStr(fuid, symbol: ",");
            if(classOrDepartmentName == "班级"){
              PersonalClassWidget.navigatorPush(context, faceUserInfoBean,"UnallocatedDepartmentStaffWidget");
            }
            if(classOrDepartmentName == "部门"){
              //跳转到部门
              PersonalDepartmentWidget.navigatorPush(context, faceUserInfoBean,"UnallocatedDepartmentStaffWidget").then((value){
                selectRecordsBeanList = new List<RecordsBean>();
                setState(() { });
              });
            }
          }else{
            VgToastUtils.toast(context, "请选择需要设置的人员");
          }
        },
        child: Text(
          "设置${classOrDepartmentName}",
          style: TextStyle(color:selectLength?Colors.white: Color(0xFF5E687C)),
        ),
        color:selectLength?Colors.blue : Color(0xFF3A3F50),
        elevation: 40,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(22.5),
        ),
      ),
    );
  }

  Widget _toFunctionBar() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        selectAll = !selectAll;
        if(selectAll){
          recordsBeanList?.forEach((element) {
            //判断去除已设置为true的选项
            if(!(element?.isSelected??false)){
              selectRecordsBeanList?.add(element);
              fuid?.add(element?.fuid);
            }
            element?.isSelected = true;
          });
        }else{
          recordsBeanList?.forEach((element) {
            element?.isSelected = false;
            fuid?.remove(element?.fuid);
            selectRecordsBeanList?.remove(element);

          });
        }
        setState(() {});
      },
      child: Container(
        height: 45,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        alignment: Alignment.centerLeft,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Image.asset(
                selectAll
                    ? "images/common_selected_ico.png"
                    : "images/common_unselect_ico.png",
                height: 20,
              ),
            ),
            Text(
              "全选",
              style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 15),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toListBean() {
    return ListView.separated(
        itemCount: recordsBeanList?.length??0,
        padding: const EdgeInsets.all(0),
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        itemBuilder: (BuildContext context, int index) {
          return _toListItemWidget(context, recordsBeanList[index]);
        },
        separatorBuilder: (BuildContext context, int index) {
          return SizedBox(
            height: 0,
          );
        });
  }

  Widget _toListItemWidget(BuildContext context,RecordsBean recordsBean) {
    return Container(
      height: 60,
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: _toMainRowWidget(context,recordsBean),
    );
  }

  Widget _toMainRowWidget(BuildContext context,RecordsBean recordsBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        recordsBean?.isSelected = !(recordsBean?.isSelected ??false);
        if(recordsBean?.isSelected){
          selectRecordsBeanList?.add(recordsBean);
          fuid?.add(recordsBean?.fuid);
          //判断选中数据长度
          if(selectRecordsBeanList?.length == recordsBeanList?.length){
            selectAll = true;
          }
        }else{
          fuid?.remove(recordsBean?.fuid);
          selectRecordsBeanList?.remove(recordsBean);
          selectAll = false;
        }
        setState(() {});
      },
      child: Row(
        children: <Widget>[
          _toImageSelect(recordsBean),
          SizedBox(
            width: 15,
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Stack(
              children: <Widget>[
                Container(
                  width: 36,
                  height: 36,
                  child: VgCacheNetWorkImage(
                    showOriginEmptyStr(recordsBean?.napicurl) ?? (recordsBean?.putpicurl ?? ""),
                    fit: BoxFit.cover,
                    imageQualityType: ImageQualityType.middleDown,
                    defaultErrorType: ImageErrorType.head,
                    defaultPlaceType: ImagePlaceType.head,
                  ),
                ),
                // _specialAttentionImg(),
              ],
            ),
          ),
          SizedBox(
            width: 10,
          ),
          Container(
            height: 36,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    (false)
                        ? Text(
                            "未知",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                color: ThemeRepository.getInstance()
                                    .getMinorRedColor_F95355(),
                                fontSize: 15,
                                height: 1.2),
                          )
                        : CommonNameAndNickWidget(
                            name: "${recordsBean?.name??""}",
                            nick: "${recordsBean?.nick??""}",
                          ),
                    // VgLabelUtils.getRoleLabel(
                    //     companyDetailByTypeListItemBean?.roleid ?? "10") ??
                    //     Container(),
                    _toPhoneWidget(recordsBean?.phone??""),
                  ],
                ),
                SizedBox(
                  height: 2,
                ),
                //判断如果部门项目城市班级不为空那么就显示出来。否则显示手机号
                // if (!VgStringUtils.checkAllEmpty([
                //   companyDetailByTypeListItemBean?.department?.trim(),
                //   companyDetailByTypeListItemBean?.projectname?.trim(),
                //   companyDetailByTypeListItemBean?.city?.trim(),
                //   companyDetailByTypeListItemBean?.classname?.trim(),
                //   // companyDetailByTypeListItemBean?.coursename?.trim(),
                // ]))
                Expanded(
                  child: Builder(builder: (BuildContext context) {
                    return CommonConstraintMaxWidthWidget(
                      maxWidth: ScreenUtils.screenW(context) / 2,
                      child: Text(
                        "${recordsBean?.uname??"${UserRepository.getInstance().userData.comUser.name}"}添加",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: VgColors.INPUT_BG_COLOR,
                          fontSize: 12,
                        ),
                      ),
                    );
                  }),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _toImageSelect(RecordsBean recordsBean) {
    return Container(
        width: 20,
        height: 20,
        child: Image.asset(
            recordsBean?.isSelected ??false
                ? "images/common_selected_ico.png"
                : "images/common_unselect_ico.png",
            height: 20));
  }

  Widget _toPhoneWidget(String phone) {
    return Offstage(
      //当offstage为true，控件隐藏； 当offstage为false，显示
      offstage: phone!=""?false:true,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }
}
